package com.zxjbyte.yiyi.framework.web.filter;

import com.zxjbyte.yiyi.framework.common.util.ServletXUtil;
import com.zxjbyte.yiyi.framework.web.context.CryptoAlgorithm;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

/**
 * 处理入参解密
 * @Author zhangxingjia
 * @Date 2025/10/31 17:43
 * @Version: 1.0
 */
public class ApiDecryptionRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public ApiDecryptionRequestWrapper(HttpServletRequest request, Object cryptoInstance, CryptoAlgorithm cryptoAlgorithm) {
        super(request);
        String requestBody = ServletXUtil.getBody(request);
        body = cryptoAlgorithm.decrypt(requestBody, cryptoInstance);
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public int getContentLength() {
        return body.length;
    }

    @Override
    public long getContentLengthLong() {
        return body.length;
    }

    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream stream = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public int read() {
                return stream.read();
            }

            @Override
            public int available() {
                return body.length;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

        };
    }
}
